package br.com.hstar.server.config;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import br.com.hstar.client.config.CadQuartoService;
import br.com.hstar.client.config.CadQuartoUI;
import br.com.hstar.model.config.CadQuartoDO;
import br.com.hstar.server.DozerHelper;
import br.com.hstar.server.DozerUtility;
import br.com.hstar.server.HibernateUtility;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class CadQuartoServiceImpl extends RemoteServiceServlet implements CadQuartoService {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void saveOrUpdate(CadQuartoUI objUI) {
		CadQuartoDO objDO = (CadQuartoDO) DozerUtility.getMapper().map(objUI, CadQuartoDO.class);
		
		Session sessao = HibernateUtility.getSession();
		Transaction transaction = sessao.beginTransaction();
		
		if(objUI.getId() != null) {
			sessao.update(objDO);
		} else {
			sessao.save(objDO);
		}

		transaction.commit();
		sessao.close();
	}
	
	public List listAll() {
		Session sessao = HibernateUtility.getSession();
		Criteria select = sessao.createCriteria(CadQuartoDO.class);
		ArrayList objetos = (ArrayList)select.list();
		sessao.close();
		
		return DozerHelper.mapList(
				DozerUtility.getMapper(), 
				objetos, 
				CadQuartoUI.class);
	}
	
	public CadQuartoUI retrieveById(Long id) {
		Session sessao = HibernateUtility.getSession();
		Criteria cri = sessao.createCriteria(CadQuartoDO.class);
		cri.add(Restrictions.eq("id", id));
		CadQuartoDO objDO = (CadQuartoDO) cri.uniqueResult();
		sessao.close();
				
		CadQuartoUI objUI = (CadQuartoUI) DozerUtility.getMapper().map(objDO, CadQuartoUI.class);
		
	  	return objUI;
	}
	
	public CadQuartoUI retrieveByNumero(Integer numero) {
		Session sessao = HibernateUtility.getSession();
		Criteria cri = sessao.createCriteria(CadQuartoDO.class);
		cri.add(Restrictions.eq("numero", numero));
		CadQuartoDO objDO = (CadQuartoDO) cri.uniqueResult();
		sessao.close();
				
		CadQuartoUI objUI = (CadQuartoUI) DozerUtility.getMapper().map(objDO, CadQuartoUI.class);
		
	  	return objUI;
	}
	
	public void delete(Long id) {
		Session sessao = HibernateUtility.getSession();
		Transaction transaction = sessao.beginTransaction();

			Criteria cri = sessao.createCriteria(CadQuartoDO.class);
			cri.add(Restrictions.eq("id", id));
			CadQuartoDO objDO = (CadQuartoDO) cri.uniqueResult();
			sessao.delete(objDO);

		transaction.commit();
		sessao.close();
	}
}
